const fs = require('fs');
const path = require('path');
var tools = require('../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

const functions = require(tools.appPath + 'functions');

const Auth = require(tools.controllerPath+'common/auth.js');

var md5 = require('md5');

module.exports = class extends Auth {
  async __before() {
    const flag = await super.__before();
    if (flag === false) return false;

    this.moduleid = 1;
    this.MD = this.CORE_CONF.mod_single(this.moduleid);
    functions.copy_setting(this.moduleid);
    this._setting = functions.load_setting(this.moduleid);
    this.assign({
      MODULEID: this.moduleid,
      MD: this.MD,
    });
    return true;
  }

  index(req, res) {
    res.end('admin/index');
  }

  async safe() {
    let post = this.post();
    if (this.isPost && Object.keys(post).length > 0) {
      let old_password = functions.trim(post['old_password']);
      let new_password = functions.trim(post['new_password']);
      let new_password2 = functions.trim(post['new_password2']);
      if (!old_password || !new_password || !new_password2) {
        this.msg(0, '请填写完密码后再提交');
        return;
      }
      if (new_password != new_password2) {
        this.msg(0, '两次新密码不一致');
        return;
      }
      let userid = this.auth['userid'];
      let user = await model.find("select * from szh_member where userid=?", [userid]);
      if (md5(old_password) != user['password']) {
        this.msg(0, '旧密码不正确');
        return;
      }
      let r = await model.u("update szh_member set ? where userid=?", { password: md5(new_password) }, [userid]);
      this.msg(r);
      return;
    }
    return this.tpl();
  }

  async setting() {
    let post = this.post();
    if (this.isPost && Object.keys(post).length > 0) {
      let r = functions.save_setting(this.moduleid, post);
      this.msg(r);
      return;
    }
    let setting = functions.load_setting(this.moduleid);
    this.assign({
      setting: setting,
    })
    return this.tpl();
  }

};
